<template>
  <a-modal width="50%" :bodyStyle="{ height: '550px', overflow: 'auto' }" v-model="isModel" :title="labelTitle">
    <a-form-model
      ref="agentPersonAddRef"
      :rules="rules"
      style="width: 100%"
      labelAlign="left"
      :model="agentPersonForm"
    >
      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="代理人类型" prop="type" has-feedback>
          <a-select allow-clear placeholder="请选择代理人类型" v-model="agentPersonForm.type">
            <a-select-option v-for="item in Tp_agentList" :key="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="代理申请人/第三人" prop="applicantname" has-feedback>
          <a-select allow-clear placeholder="请选择代理申请人/第三人" v-model="agentPersonForm.applicantname" >
            <a-select-option v-for="item in selectUserList" :key="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="姓名"
          prop="name">
          <a-input
            v-model="agentPersonForm.name"
            allow-clear
            :maxLength="125"
            placeholder="请输入姓名" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.LEGAL">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="证件类型"
          prop="cardtype"
          has-feedback
        >
          <a-select allow-clear placeholder="请选择证件类型" v-model="agentPersonForm.cardtype">
            <a-select-option v-for="item in Tp_card" :key="item.id">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="证件号"
          prop="cardno">
          <a-input
            v-model="agentPersonForm.cardno"
            allow-clear
            :maxLength="125"
            placeholder="请输入证件号" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.LAWYER || agentPersonForm.type == Tp_agentValue.LEGAL">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="性别"
          prop="gender"
        >
          <a-select allow-clear placeholder="请选择性别" v-model="agentPersonForm.gender">
            <a-select-option v-for="item in Tp_gender" :key="item.id">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.LAWYER || agentPersonForm.type == Tp_agentValue.LEGAL">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="民族"
          prop="nation"
        >
          <a-select allow-clear placeholder="请选择民族" v-model="agentPersonForm.nation">
            <a-select-option v-for="item in Tp_nation" :key="item.id">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="联系电话" prop="tel">
          <a-input v-model="agentPersonForm.tel" allow-clear :maxLength="125" placeholder="请输入联系电话" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.LAWYER || agentPersonForm.type == Tp_agentValue.CITIZEN">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="工作单位（律所名称）" prop="unit">
          <a-input v-model="agentPersonForm.unit" allow-clear :maxLength="125" placeholder="请输入工作单位（律所名称）" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="送达地址/地址" prop="addr">
          <a-input v-model="agentPersonForm.addr" allow-clear :maxLength="125" placeholder="请输入送达地址/地址" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.CITIZEN">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="邮政编码" prop="postcode">
          <a-input v-model="agentPersonForm.postcode" allow-clear :maxLength="125" placeholder="请输入邮政编码" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item
          label="委托书"
          prop="fileentrust"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-upload
            :accept="acceptFileType"
            :file-list="fileentrustList"
            :remove="(file) => removeFile(file, 0)"
            name="file"
            :multiple="true"
          >
            <a-button icon="upload" @click.stop="uploadFile(0)"> 上传 </a-button>
          </a-upload>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.CITIZEN">
        <a-form-model-item
          label="身份证明"
          prop="filecard"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-upload
            :accept="acceptFileType"
            :file-list="filecardList"
            :remove="(file) => removeFile(file, 1)"
            name="file"
            :multiple="true"
          >
            <a-button icon="upload" @click.stop="uploadFile(1)"> 上传</a-button>
          </a-upload>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="agentPersonForm.type == Tp_agentValue.LAWYER || agentPersonForm.type == Tp_agentValue.LEGAL">
        <a-form-model-item
          label="身份证明书"
          prop="doccard"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-upload
            :accept="acceptFileType"
            :file-list="doccardList"
            :remove="(file) => removeFile(file, 2)"
            name="file"
            :multiple="true"
          >
            <a-button icon="upload" @click.stop="uploadFile(2)"> 上传</a-button>
          </a-upload>
        </a-form-model-item>
      </a-col>

    </a-form-model>

    <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>
    <template slot="footer">
      <div style="display: flex; justify-content: center">
        <a-button class="m-r-8" icon="cancel" @click="onClose"> 取消 </a-button>
        <a-button
          class="m-r-8"
          type="primary"
          @click="onSubmit"
          icon="save"
          :loading="loading"
          v-if="applyid != ''">
          保存
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import { nanoid } from 'nanoid'
import { minioUpload, minioRemove, minioUploadMore } from '@/api/base/file'
import { Tp_agentList, Tp_agentValue } from '@/enumeration/Tp_agent'
import { queryEnumeration } from '@/api/accept/enum_load'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'
import { saveMaterialRepeat } from '@/api/accept/aprv_process_materials'
import { Tp_procmaterialValue } from '@/enumeration/Tp_procmaterial'
import { Tp_proctypeValue } from '@/enumeration/Tp_proctype'
import { APP_USER } from '@/store/mutation-types.js'
import storage from 'store'
import { getApplicantAndThirdList } from '@/api/accept/apl_applicant'
import { saveAgent } from '@/api/accept/apl_agent'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    }
  },
  data () {
    return {
      labelCol: { span: 8 }, // label宽
      wrapperCol: { span: 12 }, // 组件宽
      loading: false, // 按钮显示
      isModel: false, // 模态框显示
      Tp_agentList: Tp_agentList,
      Tp_agentValue: Tp_agentValue,
      Tp_card: [], // 证件类型
      Tp_gender: [], // 性别
      Tp_nation: [], // 民族
      agentPersonForm: {
        id: undefined, // id
        applyid: undefined, // applyid
        type: undefined, // 代理人类型
        name: undefined, // 名称
        cardtype: undefined, // 证件类型
        cardno: undefined, // 证件号
        gender: undefined, // 性别
        nation: undefined, // 民族
        addr: undefined, // 送达地址（住址）
        unit: undefined, // 工作单位（律所名称）
        tel: undefined, // 电话
        postcode: undefined, // 邮政编码
        applicantname: undefined, // 代理申请人/第三人
        filecard: undefined, // 身份证明
        doccard: undefined, // 身份证明书
        fileentrust: undefined // 委托书
      },
      filecardList: [], // 身份证明文件
      doccardList: [], // 身份证明书文件
      fileentrustList: [], // 委托书文件
      /**
       * 添加表单验证规则
       */
       rules: {
        type: [{ required: true, message: '请选择代理人类型', trigger: 'change' }],
        applicantname: [{ required: true, message: '请选择代理申请人/第三人类型', trigger: 'change' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        cardno: [{ validator: this.checkCardno }],
        tel: [{ validator: this.checkTel }],
        postcode: [{ validator: this.checkPostcode }]
      },
      labelTitle: '',
      acceptFileType: FILETYPE,
      operateType: undefined,
      Tp_procmaterialValue: Tp_procmaterialValue,
      Tp_proctypeValue: Tp_proctypeValue,
      currentUser: storage.get(APP_USER),
      deleteFileList: [], // 删除的文件列表
      selectUserList: [],
    }
  },
  components: {
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  async created () {
    this.queryEnumeration('Tp_card', (val) => {
      this.Tp_card = val
    })
    this.queryEnumeration('Tp_gender', (val) => {
      this.Tp_gender = val
    })
    this.queryEnumeration('Tp_nation', (val) => {
      this.Tp_nation = val
    })
    this.selectUserList = []
    const res = await getApplicantAndThirdList(this.applyid)
    if (res.code == 0) {
      this.selectUserList = [...res.data.applicant, ...res.data.third]
    } else {
      this.selectUserList = []
    }
  },
  methods: {

    init (isEdit, editForm) {
      this.isModel = true
      if (isEdit) {
        this.labelTitle = '编辑代理人'
        this.resetFileList()
        this.agentPersonForm = Object.assign({}, this.agentPersonForm, editForm)
        if (editForm.filecardList != null && editForm.filecardList != undefined) {
          editForm.filecardList.forEach(item => {
            const file = {
              uid: item.id,
              name: item.filename,
              status: 'done',
              url: item.path,
              flag: item.id
            }
            this.filecardList.push(file)
          })
        }
        if (editForm.doccardList != null && editForm.doccardList != undefined) {
          editForm.doccardList.forEach(item => {
            const file = {
              uid: item.id,
              name: item.filename,
              status: 'done',
              url: item.path,
              flag: item.id
            }
            this.doccardList.push(file)
          })
        }
        if (editForm.fileentrustList != null && editForm.fileentrustList != undefined) {
          editForm.fileentrustList.forEach(item => {
            const file = {
              uid: item.id,
              name: item.filename,
              status: 'done',
              url: item.path,
              flag: item.id
            }
            this.fileentrustList.push(file)
          })
        }
      } else {
        this.labelTitle = '新增代理人'
        this.agentPersonForm = {
          id: undefined, // id
          applyid: undefined, // applyid
          type: undefined, // 代理人类型
          name: undefined, // 名称
          cardtype: undefined, // 证件类型
          cardno: undefined, // 证件号
          gender: undefined, // 性别
          nation: undefined, // 民族
          addr: undefined, // 送达地址（住址）
          unit: undefined, // 工作单位（律所名称）
          tel: undefined, // 电话
          postcode: undefined, // 邮政编码
          applicantname: undefined, // 代理申请人/第三人
          filecard: undefined, // 身份证明
          doccard: undefined, // 身份证明书
          fileentrust: undefined // 委托书
        }
        this.resetFileList()
        this.agentPersonForm.id = this.applyid + nanoid()
        this.agentPersonForm.applyid = this.applyid
        if (this.applyid == '' || this.applyid == undefined) {
          this.$message.error('当前传入的applyid为空, 无法正常新增')
          this.isModel = false
        }
        this.resetForm()
      }
    },
    /*
    * 查询枚举值
    */
    async queryEnumeration (val, callback) {
      await queryEnumeration({ 'enName': val }).then((res) => {
        if (res.code !== 0) {
          console.log('查询枚举值错误')
        } else {
          callback(res.data)
        }
      })
    },
    checkCardno (rule, value, callback) {
      if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error('证件号码不正确'))
      }
      callback()
    },
    checkTel (rule, value, callback) {
      if (value && !/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/.test(value)) {
        callback(new Error('联系号码不正确'))
      }
      callback()
    },
    checkPostcode (rule, value, callback) {
      if (value && !/^[0-9]{6}$/.test(value)) {
        callback(new Error('邮政编码不正确'))
      }
      callback()
    },

    /**
    * 关闭页面
    */
    onClose () {
      this.resetForm()
      this.isModel = false
    },
    resetFileList () {
      this.filecardList = [] // 身份证明文件
      this.doccardList = [] // 身份证明书文件
      this.fileentrustList = []
    },
    /**
     * 重置表单
     */
     resetForm () {
      console.log('form', this.$refs.agentPersonAddRef)
      if (this.$refs.agentPersonAddRef) {
        this.$refs.agentPersonAddRef.clearValidate()
      }
      this.resetFileList()
    },

    removeFile (file, type) {
      if (type === 0) {
        this.fileentrustList = this.fileentrustList.filter((item) => item.uid !== file.uid)
      } else if (type === 1) {
        this.filecardList = this.filecardList.filter((item) => item.uid !== file.uid)
      } else if (type === 2) {
        this.doccardList = this.doccardList.filter((item) => item.uid !== file.uid)
      }
      this.deleteFileList.push(file.uid)
    },
    minioRemove (fileId) {
      minioRemove({ 'fileid': fileId }).then((res) => {
        console.log('res', res)
        if (res.code !== 0) {
          console.log('删除文件失败', res)
        } else {
          console.log('删除文件成功', fileId)
        }
      })
    },
    // 上传附件
    uploadFile (operateType) {
      // this.selectData = record
      this.operateType = operateType
      this.$refs.multiUploadBasic.importVisible = true
    },
    /**
     * 确定保存导入数据
     */
    importFileFun (importFileList) {
      let _this = this
      console.log('importFileList', importFileList)
      const files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.$refs.multiUploadBasic.loading = true
      if (this.operateType == null || this.operateType == undefined) {
        this.$message.error('操作类型为空')
      }
      minioUploadMore(files).then((res) => {
        if (res.code == 0) {
          const attachs = res.data
          attachs.forEach((attach) => {
            const file = {
              uid: attach.id,
              name: attach.filename,
              status: 'done',
              url: attach.url,
              flag: attach.id
            }
            if (this.operateType === 0) {
              _this.fileentrustList.push(file)
            } else if (this.operateType === 1) {
              _this.filecardList.push(file)
            } else if (this.operateType === 2) {
              _this.doccardList.push(file)
            }
          })
          this.$message.success('上传成功')
          this.$refs.multiUploadBasic.handleCancel()
        } else {
          this.$message.success('上传失败')
          this.$refs.multiUploadBasic.handleCancel()
        }
      }).finally(() => {
        this.$refs.multiUploadBasic.loading = false
      })
    },

    /**
     * 提交表单
     */
     onSubmit () {
      const _this = this
      this.$refs.agentPersonAddRef.validate((valid) => {
        _this.loading = true
        if (valid) {
          if (_this.fileentrustList != null && _this.fileentrustList.length > 0) {
            const uploadFile = []
            _this.fileentrustList.forEach((item) => {
              uploadFile.push(item.uid)
            })
            _this.agentPersonForm.fileentrust = uploadFile.join(',')
          } else {
            _this.agentPersonForm.fileentrust = ''
          }
          if (_this.filecardList != null && _this.filecardList.length > 0) {
            const uploadFile = []
            _this.filecardList.forEach((item) => {
              uploadFile.push(item.uid)
            })
            _this.agentPersonForm.filecard = uploadFile.join(',')
          } else {
            _this.agentPersonForm.filecard = ''
          }
          if (_this.doccardList != null && _this.doccardList.length > 0) {
            const uploadFile = []
            _this.doccardList.forEach((item) => {
              uploadFile.push(item.uid)
            })
            _this.agentPersonForm.doccard = uploadFile.join(',')
          } else {
            _this.agentPersonForm.doccard = ''
          }

          // 通过类型来重置部分值
          if (this.agentPersonForm.type === this.Tp_agentValue.LAWYER) {
            this.agentPersonForm.cardtype = undefined
            this.agentPersonForm.postcode = undefined
            this.agentPersonForm.filecardList = []
            this.agentPersonForm.filecard = undefined
          } else if (this.agentPersonForm.type === this.Tp_agentValue.LEGAL) {
            this.agentPersonForm.unit = undefined
            this.agentPersonForm.postcode = undefined
            this.agentPersonForm.filecardList = []
            this.agentPersonForm.filecard = undefined
          } else if (this.agentPersonForm.type === this.Tp_agentValue.CITIZEN) {
            this.agentPersonForm.doccardList = []
            this.agentPersonForm.doccard = undefined
          }
          saveAgent (this.agentPersonForm).then((res) => {
            _this.loading = false
            if (res.code !== 0) {
              _this.$message.error('委托代理人保存失败')
            } else {
              _this.$message.success('保存成功')
              if (this.deleteFileList && this.deleteFileList.length > 0) {
                this.deleteFileList.forEach((fileId) => {
                  this.minioRemove(fileId)
                })
              }
              _this.$emit('requery')
              _this.onClose()
            }
          })
        } else {
          _this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            // console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    }

  }
}
</script>

<style>

</style>